package com.dayu.finecomm.utils;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.bson.BsonArray;
import org.bson.BsonDateTime;
import org.bson.BsonDocument;
import org.bson.BsonInt32;
import org.bson.BsonInt64;
import org.bson.BsonNull;
import org.bson.BsonString;
import org.bson.BsonValue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class BsonTool {
	/**
	 * Java对象转BsonValue对象
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static BsonValue objectToBsonValue(Object obj) {
		if (obj instanceof Integer) {
			return new BsonInt32((Integer) obj);
		}

		if (obj instanceof String) {
			return new BsonString((String) obj);
		}

		if (obj instanceof Long) {
			return new BsonInt64((Long) obj);
		}

		if (obj instanceof Date) {
			return new BsonDateTime(((Date) obj).getTime());
		}

		if (obj instanceof List) {
			return ListToBsonArray((List<?>) obj);
		}

		if (obj instanceof Object) {
			JSONObject jo = JSONObject.parseObject(JSON.toJSONString(obj));
			BsonDocument document = new BsonDocument();
			if (!jo.isEmpty()) {
				Set<String> set = jo.keySet();
				for (String key : set) {
					document.put(key, BsonTool.objectToBsonValue(jo.get(key)));
				}
			}
			return document;
		}
		return new BsonNull();
	}

	public static BsonArray ListToBsonArray(List<?> list) {
		JSONArray userData = JSONArray.parseArray(JSON.toJSONString(list));
		BsonArray bsonArray = new BsonArray();
		JSONObject jo;
		for (int i = 0; i < userData.size(); i++) {
			if (userData.get(i) instanceof Integer) {
				bsonArray.add(new BsonInt32((Integer) userData.get(i)));
			} else if (userData.get(i) instanceof String) {
				bsonArray.add(new BsonString((String) userData.get(i)));
			} else if (userData.get(i) instanceof Long) {
				bsonArray.add(new BsonInt64((Long) userData.get(i)));
			} else if (userData.get(i) instanceof Date) {
				bsonArray.add(new BsonDateTime(((Date) userData.get(i)).getTime()));
			} else {
				jo = userData.getJSONObject(i);
				BsonDocument document = new BsonDocument();
				if (!jo.isEmpty()) {
					Set<String> set = jo.keySet();
					for (String key : set) {
						document.put(key, BsonTool.objectToBsonValue(jo.get(key)));
					}
				}
				bsonArray.add(document);
			}
		}
		return bsonArray;
	}
}
